package com.example.library.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.library.common.Constants;
import com.example.library.common.LoginUser;
import com.example.library.common.Result;
import com.example.library.entity.User;
import com.example.library.entity.UserDTO;
import com.example.library.exception.ServiceException;
import com.example.library.mapper.UserMapper;
import com.example.library.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.library.utils.JwtUtil;
import com.example.library.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.scanner.Constant;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 胡绍杆
 * @since 2022-06-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserService userService;

    @Override
    public Result login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getAccount(),user.getPassword());
        QueryWrapper<User> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("account",user.getAccount());
        List<User> list = userService.list(queryWrapper1);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if(list.size()!=0)
        {
            boolean matches = encoder.matches(user.getPassword(), list.get(0).getPassword());
            if (matches==false) {
                return Result.error(Constants.CODE_801,"用户名或密码错误");
            }
        }
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
//            return Result.error(Constants.CODE_801,"用户名或密码错误");
            throw new ServiceException(Constants.CODE_801,"用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getAccount();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
//        HashMap<String,String> map = new HashMap<>();
//        map.put("token",jwt);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        User one = userService.getOne(queryWrapper);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(one,userDTO);
        userDTO.setToken(jwt);
        return Result.success(userDTO);
    }

    @Override
    public Result logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String account = loginUser.getUser().getAccount();
        redisCache.deleteObject("login:"+account);
        return Result.success();
    }

    @Override
    public Result changePassword(String account, String newPassword) {
        UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String pwd=encoder.encode(newPassword);
        updateWrapper.eq("account",account).set("password",pwd);
        userService.update(updateWrapper);
        return Result.success();
    }


//    @Override
//    public Result register(User user) {
//        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
//
//        queryWrapper.eq("account",user.getAccount());
//        queryWrapper.eq("password",user.getPassword());
//
//        User one=getOne(queryWrapper);
//        if (one==null){
//            one=new User();
//            BeanUtil.copyProperties(user,one,true);
//            save(one);
//        }
//        else {
//            return Result.error(Constants.CODE_400,"用户已经存在");
//        }
//        return Result.success(one);
//    }


}
